package com.example.demo.controller;


import ch.qos.logback.core.util.StringUtil;
import com.example.demo.constants.Constants;
import com.example.demo.enums.BookStatusEnum;
import com.example.demo.model.BookInfo;
import com.example.demo.model.PageRequest;
import com.example.demo.model.PageResponse;
import com.example.demo.model.ResultVO;
import com.example.demo.service.BookService;
import com.example.demo.model.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {


    @Autowired
    private BookService bookService;

//    @PostMapping("/getList")
//    public List<BookInfo> getList(){
////        BookService bookService = new BookService();
//        List<BookInfo> bookInfos = bookService.getBookList();
//        return bookInfos;
//    }

//    @RequestMapping(value = "/addBook", produces = "application/json")
//    public String addBook(BookInfo bookInfo){
//        log.info("添加图书, bookInfo:{}", bookInfo);
//
//        //参数校验
//        if(!StringUtils.hasLength(bookInfo.getBookName())
//        || !StringUtils.hasLength(bookInfo.getAuthor())
//        || bookInfo.getCount() == null
//        || bookInfo.getPrice() == null
//        || !StringUtils.hasLength(bookInfo.getPublish())){
//            return "参数不合法, 请重新检查";
//        }
//        //2,插入数据
//        try{
//            Integer result = bookService.insertBook(bookInfo);
//            if(result == 1){
//                return "";
//            }
//        }catch (Exception e){
//            log.error("数据插入发生异常, e: ", e);
//        }
//        return "数据插入失败,请联系管理员";
//    }

    //添加图书
    @RequestMapping(value = "/addBook", produces = "application/json")
    public ResultVO<String> addBook(BookInfo bookInfo) {
        log.info("添加图书, bookInfo:{}", bookInfo);

        //参数校验
        if (!StringUtils.hasLength(bookInfo.getBookName())
                ||!StringUtils.hasLength(bookInfo.getAuthor())
                || bookInfo.getCount() == null
                || bookInfo.getPrice() == null
                ||!StringUtils.hasLength(bookInfo.getPublish())) {
            return new ResultVO<>(400, "参数不合法，图书名称、作者、库存、价格、出版社均为必填项", "");
        }

        //2,插入数据
        try {
            Integer result = bookService.insertBook(bookInfo);
            if (result == 1) {
                return new ResultVO<>(200, "图书添加成功", "");
            }
            return new ResultVO<>(500, "图书添加失败，插入结果异常", "");
        } catch (Exception e) {
            log.error("数据插入发生异常, e: ", e);
            return new ResultVO<>(500, "数据插入失败，请联系管理员，具体异常：" + e.getMessage(), "");
        }
    }

    //查询图书信息,翻页使用
    @RequestMapping("/getListByPage")
    public Result<PageResponse<BookInfo>> getListByPage(PageRequest pageRequest, HttpServletRequest request) {
        log.info("获取图书列表, pageRequest: {}", pageRequest);

//        HttpSession session = request.getSession(false);//如果拿不到session就会返回null
//        if(session == null
//        || session.getAttribute(Constants.SESSION_USER_KEY) == null
//        || !StringUtils.hasLength((String)session.getAttribute(Constants.SESSION_USER_KEY))){
//            //用户未登录
//            return Result.unlogin();
//        }
        //参数校验省略
        PageResponse<BookInfo> bookInfoPageResponse = new PageResponse<>();
        try{
            bookInfoPageResponse = bookService.getListByPage(pageRequest);

        }catch(Exception e){
            log.error("获取图书列表失败");
            return Result.fail();
        }
        return Result.success(bookInfoPageResponse);
    }


    //通过id查询图书
    @RequestMapping("/queryBookById")
    public BookInfo queryBookById(Integer bookId){
//        long start = System.currentTimeMillis();
        log.info("获取图书信息, bookId: "+ bookId);
        //参数校验,不能为null,不能<=0...省略
        BookInfo bookInfo = bookService.queryBookById(bookId);

//        long end = System.currentTimeMillis();
//        log.info("queryBookById 耗时: " + (end - start) + "ms");
        return bookInfo;
    }

//    @RequestMapping("/updateBook")
//    public String updateBook(BookInfo bookInfo){
//        log.info("更新图书, bookInfo: {}", bookInfo);
//        try{
//            Integer result = bookService.updateBook(bookInfo);
//            if(result > 0){//1
//                return "";
//            }
//            return "图书更新失败";
//        }catch(Exception e){
//            log.error("更新图书失败,e:",e);
//            return "数据库操作失败";
//        }
//
//    }

    //更新图书
    @RequestMapping("/updateBook")
    public ResultVO<String> updateBook(BookInfo bookInfo) {
        log.info("更新图书, bookInfo: {}", bookInfo);
        try {
            Integer result = bookService.updateBook(bookInfo);
            if (result > 0) {
                return new ResultVO<>(200, "图书更新成功", "");
            } else if (result == 0) {
                return new ResultVO<>(200, "图书内容未发生变化，无需更新", "");
            }
            return new ResultVO<>(500, "图书更新失败", "");
        } catch (Exception e) {
            log.error("更新图书失败,e:", e);
            return new ResultVO<>(500, "数据库操作失败：" + e.getMessage(), "");
        }
    }
    @RequestMapping(value = "/deleteBook", produces = "application/json")//string类型转为json
    public String deleteBook(Integer bookId){//返回类型尽量不要使用String类型,
        log.info("删除图书, bookId: {}", bookId);
        try{
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(bookId);
            bookInfo.setStatus(BookStatusEnum.DELETED.getCode());
            Integer result = bookService.updateBook(bookInfo);
            if(result > 0){//1
                return "";
            }
            return "图书删除失败";
        }catch(Exception e){
            log.error("删除图书失败,e:",e);
            return "数据库操作失败";
        }

    }

    //批量删除
    @RequestMapping("/batchDeleteBook")
    public Boolean batchDeleteBook(@RequestParam List<Integer> ids){
        log.info("批量删除图书, ids:{}", ids);
        try{
            //执行sql
            bookService.batchDeleteBook(ids);
            return true;

        }catch(Exception e){
            log.error("批量删除图书, ids:{}", ids);
        }
        return false;
    }
}
